#!/bin/bash

# 创建证据目录
mkdir -p evidence

# 设置基本参数
BASE="http://localhost:3000"
TOKEN="$(cat backend/scripts/token.txt)"

# 1) 上传校验（注意字段名必须是 file，不要自己加 content-type）
echo "1. 上传校验测试"
curl -sS -X POST "$BASE/api/admin/menu-import/v2/validate" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file=@backend/menu_template.xlsx" | tee evidence/validate.json

jq -r .job_id evidence/validate.json   # ← 必须输出一个 job_id
JOB=$(jq -r .job_id evidence/validate.json)
echo "获取到job_id: $JOB"

# 2) 轮询状态（最多 30s）
echo "\n2. 轮询状态测试"
for i in {1..40}; do
  curl -sS "$BASE/api/admin/menu-import/v2/jobs/$JOB" -H "Authorization: Bearer $TOKEN" \
  | tee "evidence/job_$i.json"
  STATUS=$(jq -r .job.status "evidence/job_$i.json"); echo "poll#$i $STATUS"
  [[ "$STATUS" == "validated" || "$STATUS" == "failed" ]] && break
  sleep 0.8
done

# 3) 提交导入（注意：job_id 放 query，幂等键放 body；如果你们契约相反，就两端统一）
echo "\n3. 提交导入测试"
curl -sS -X POST "$BASE/api/admin/menu-import/v2/commit?job_id=$JOB" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"idempotency_key\":\"$JOB\"}" | tee evidence/commit.json

echo "\n测试完成，证据已保存到evidence目录"